// index.js
// 获取应用实例
const app = getApp()
const api = require("../../utils/request");

Page({
  data: {
    // tabs: [{
    //     url: '/pages/bracelet-borrow/bracelet-borrow',
    //     desc: '借手环',
    //     src: `${api.apiHttp}/images/hand.png`
    //   },
    //   {
    //     url: '/pages/appointment/appointment',
    //     desc: '约篮球',
    //     src: `${api.apiHttp}/images/hand.png`
    //   },
    //   {
    //     url: '/pages/appointment/appointment',
    //     desc: '看医生',
    //     src: `${api.apiHttp}/images/hand.png`
    //   },
    // ],
    isSuperUser: true,

    http: api.apiHttp,
    userStatus: 0,
    qrCode: null,
    appointment: 0, // 已预约
    free: 0, // 空闲
    borrowed: 0, // 已借出
    loading: true,

    statusMenu: {
      available: 0, //未借阅，显示借
      booked: 1, // 已预约，显示二维码，可以取消
      borrowed: 2, // 已借出，在使用状态，不可取消，可归还
      finished: 3 // 已归还，显示当日已使用
    },
    tips: {
      msg: null,
      type: null,
      show: false
    },

    cancelShow: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const isSuperUser = wx.getStorageSync('is_super_user');
    this.setData({
      isSuperUser
    });
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#87D2FB',
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton();
    this.fetchData();
  },

  navigateToDetailPage(status) {
    wx.navigateTo({
      url: '/pages/qr-code-details/qr-code-details',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据, success中的回调函数的参数就是可以调用eventChannel
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          status
        })
      }
    })
  },

  borrowBand: function () {
    this.setData({
      loading: true,
    })
    api.post('/bracelet-borrow/appointment', null).then((res) => {
      console.log(res);
      if (res.code === '0' && res.msg === 'success') {
        this.setData({
          tips: {
            msg: '借用成功',
            show: true,
            type: res.msg
          }
        })
      } else {
        this.setData({
          tips: {
            msg: '借用失败，请稍后再试',
            show: true,
            type: 'error'
          }
        })
      }
      this.fetchData();
    })
  },
  superBorrowBand() {
    this.setData({
      loading: true,
    })
    api.post('/bracelet-borrow/appointment', null)
      .then(_ => {
        return api.get('/bracelet-borrow/user-current-status');
      })
      .then((res) => {
        return api.post('/bracelet-borrow/borrow', {
          jrn_no: res.data.jrn_no
        });
      })
      .then((res) => {
        if (res.code === '0' && res.msg === 'success') {
          this.setData({
            tips: {
              msg: '借用成功',
              show: true,
              type: res.msg
            }
          })
        } else {
          this.setData({
            tips: {
              msg: '借用失败，请稍后再试',
              show: true,
              type: 'error'
            }
          })
        }
        this.fetchData();
      })
      .catch(_ => {
        this.setData({
          tips: {
            msg: '借用失败，请稍后再试',
            show: true,
            type: 'error'
          }
        })
        this.fetchData();
      })
  },
  superBackBand() {
    this.setData({
      loading: true,
    })
    api.get('/bracelet-borrow/user-current-status')
      .then((res) => {
        return api.post('/bracelet-borrow/back', {
          jrn_no: res.data.jrn_no
        });
      })
      .then((res) => {
        if (res.code === '0' && res.msg === 'success') {
          this.setData({
            tips: {
              msg: '归还成功',
              show: true,
              type: res.msg
            }
          })
        } else {
          this.setData({
            tips: {
              msg: '归还失败，请稍后再试',
              show: true,
              type: 'error'
            }
          })
        }
        this.fetchData();
      })
      .catch(_ => {
        this.setData({
          tips: {
            msg: '借用失败，请稍后再试',
            show: true,
            type: 'error'
          }
        })
      })
  },

  // 扫描二维码进行详情展示
  scanQrCode(e) {
    const status = e.currentTarget.dataset.status;
    const that = this;
    wx.scanCode({
      success(result) {
        const body = {
          jrn_no: JSON.parse(result.result).jrn_no
        };
        if (status === 'borrow') {
          api.post('/bracelet-borrow/borrow', body)
            .then((res) => {
              if (res.code === '0' && res.msg === 'success') {
                that.navigateToDetailPage(status);
              }
            })
        } else if (status === 'back') {
          api.post('/bracelet-borrow/back', body)
            .then((res) => {
              if (res.code === '0' && res.msg === 'success') {
                that.navigateToDetailPage(status);
              }
            })
        }
      }
    })
  },
  bindToUrl(e) {
    const {
      url
    } = e.currentTarget.dataset.params;
    console.log(url)
    wx.navigateTo({
      url
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.setNavigationBarTitle({
      title: '刷新中'
    }) //动态设置当前页面的标题。
    wx.showNavigationBarLoading()
    this.fetchData();
  },
  onShareAppMessage: function () {
    return {
      title: '点开有奖问答',
      path: '/page/index'
    }
  },

  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },


  // 获取数据
  fetchData: function () {
    this.setData({
      loading: true,
    })
    let getUserStatusP = api.get('/bracelet-borrow/user-current-status');
    let getBraceletAmountP = api.get('/bracelet-borrow/bracelet-amount');
    Promise.all([getUserStatusP, getBraceletAmountP]).then((res) => {
      console.log(res);
      this.setData({
        userStatus: res[0].data.status,
        qrCode: res[0].data.jrn_no,
        free: res[1].data.free,
        loading: false,
        cancelShow: false,
      });
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
      wx.setNavigationBarTitle({
        title: '首页'
      })
    })
  },

  showCancel: function () {
    this.setData({
      cancelShow: true
    })
  },
  cancelBooking: function (e) {
    if (e.detail.index === 0) {
      this.setData({
        cancelShow: false
      })
    } else {
      api.post('/bracelet-borrow/delete-appointment', {
          jrn_no: this.data.qrCode
        })
        .then((res) => {
          if (res.code === '0' && res.msg === 'success') {
            this.setData({
              tips: {
                msg: '取消成功',
                show: true,
                type: res.msg
              },
            })
          } else {
            this.setData({
              tips: {
                msg: '取消失败，请稍后再试',
                show: true,
                type: 'error'
              },
            })
          }
          this.fetchData();
        })
    }
  }
})